<!--
 * @页面名称:动态加载获取到的窗体
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="dynamicForm">
    <el-dialog
      width="60%"
      class="previewModel"
      v-model="dialogVisible"
      draggable
      destroy-on-close
      :title="dynamicModal.title"
      :close-on-click-modal="false"
    >
      <div id="dynamic-form"></div>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { ref, nextTick, createApp, reactive, onMounted, toRaw, watch, watchEffect } from "vue";
import { storeToRefs } from "pinia";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import ElementPlus from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import SInput from "@/components/SInput.vue";
import SSelect from "@/components/SSelect.vue";
import TreeSelect from "@/components/STree.vue";
// import { List, Pulldown } from "vxe-table";
// import { Pulldown } from "vxe-pc-ui";
// import "vxe-pc-ui/es/vxe-pulldonw/style.css";
import Upload from "@/components/Upload/Img.vue";
import type { FormRules, FormInstance } from "element-plus";
import { useGlobalStore } from "@/stores/modules/global";
import { ButtonClick } from "./events";
// import RuleClass from "./ts/FieldRule";
import RuleClass from "./ts/FieldRule";
import { FormRuler } from "./ts/FormRule";
import { useDynamicStore } from "@/stores/modules/dynamic";
import { useDictionryStore } from "@/stores/modules/dictionary";
import { useCatalogStore } from "@/stores/modules/catalog";
import global from "@/utils/SnowflakeClass";
import vueAxios from "@/api/index";
import { isEqual } from "lodash-es";
import { transTree } from "@/utils/util";
import ACrypto from "@/utils/crypto";
import { cloneDeep } from "lodash-es";

const props = defineProps({
  dynamicModal: {
    type: Object,
    default: () => {
      return {};
    }
  },
  self: {
    // 传递过来的vue实例
    type: Object,
    default: () => {
      return {};
    }
  }
});
const globalStore = useGlobalStore();
const dynamicStore = useDynamicStore();
const dictionryStore = useDictionryStore();
const catalogStore = useCatalogStore();
// 窗体显示与否
const dialogVisible = ref(false);
// 打开弹出框,挂接动态表单
const open = () => {
  props.dynamicModal.htmlCode = ACrypto.getSS(props.dynamicModal.htmlCode);
  console.log("执行窗体打开");
  dialogVisible.value = true;
  nextTick(() => {
    getDynamicDom();
  });
};
// 挂载动态窗体
const getDynamicDom = () => {
  // 创建实例
  const app = createApp({
    components: {
      SInput,
      TreeSelect,
      Upload,
      SSelect
    },
    setup() {
      //表单绑定字段
      let modalFormData = dynamicStore.modalFormData;
      // 控制连续提交是否显示
      const { continuousSubmission } = storeToRefs(globalStore);
      //表单字段规则
      const ruleList = ref([]);
      //表单验证规则
      let formRules = reactive<FormRules>({});
      //表单实例
      const modalFormRef = ref<FormInstance>();
      //按钮加载属性
      const submitLoading = ref(false);
      //连续新增按钮加载属性
      const submitLoading2 = ref(false);
      //字典数据
      const dictionary = dictionryStore.getDictionaryObj;
      const tableName = ref(""); // 数据表表名
      const fieldName = ref(""); // 表单绑定字段名
      // 初始化构建对象（包含构建对象，字段规则等等）
      const { visibleConfig, childVisibleConfig } = dynamicStore;
      // 窗体验证规则
      if (props.dynamicModal.type === "folder") {
        formRules = visibleConfig.ValidationList.filter((v: any) => v.V_Enable === true);
        const FormRulesClass = new FormRuler(formRules);
        formRules = FormRulesClass.getValidation();
      }
      if (props.dynamicModal.type === "child") {
        formRules = childVisibleConfig.ValidationList.filter((v: any) => v.V_Enable === true);
        const FormRulesClass = new FormRuler(formRules);
        formRules = FormRulesClass.getValidation();
      }
      /**
       * @名字: 表格数据初始化
       * @详情: 根据窗体模型规则,初始化数据.主要执行init规则类型
       * @参数: 无
       * @返回值: {}
       */
      const init = () => {
        if (props.dynamicModal.type === "folder") {
          // ruleList.value = visibleConfig.FieldRule.filter((v: any) => v.FR_Enable === true);
          ruleList.value = visibleConfig.FieldRule.filter(
            (v: any) => v.FR_Enable === true || v.FR_Rule.toLowerCase().includes("jm")
          );
          tableName.value = visibleConfig.FMT.FMT_TableName;
        }
        if (props.dynamicModal.type === "child") {
          // ruleList.value = childVisibleConfig.FieldRule.filter((v: any) => v.FR_Enable === true);
          ruleList.value = childVisibleConfig.FieldRule.filter(
            (v: any) => v.FR_Enable === true || v.FR_Rule.toLowerCase().includes("jm")
          );
          tableName.value = childVisibleConfig.FMT.FMT_TableName;
        }
        // 执行字段规则类方法
        const FieldRuleClass = new RuleClass({ modalFormData: modalFormData, ruleList: ruleList.value });
        modalFormData = FieldRuleClass.ReSetEncrypt();
        if (ruleList.value && ruleList.value.length && ruleList.value.length > 0) {
          const FieldRuleClass = new RuleClass({
            modalFormData: modalFormData,
            fieldName: fieldName.value,
            ruleList: ruleList.value,
            tableName: tableName.value
          }); // 执行字段规则类方法
          FieldRuleClass.fieldRuleInit();
          console.log("执行init规则后", modalFormData);
        }
      };
      // 取消事件
      const cancel = () => {
        dialogVisible.value = false;
      };
      // 确认事件
      const onSubmit = (type: string) => {
        modalFormRef.value!.validate(valid => {
          if (valid) {
            submitLoading.value = true;
            submitAnalyse(type); // 内部执行逻辑
          } else {
            return false;
          }
        });
      };
      // 确认事件
      const onSubmit2 = (type: string) => {
        modalFormRef.value!.validate(valid => {
          if (valid) {
            submitLoading2.value = true;
            submitAnalyse(type); // 内部执行逻辑
          } else {
            return false;
          }
        });
      };
      // 失焦
      const changeTrigger = (field: string) => {
        // fieldName.value = field;
      };
      // 输入框改变事件
      const input = (field: string) => {
        fieldName.value = field;
      };
      // 选择框改变事件
      const selectChange = (field: strin) => {
        fieldName.value = field;
      };
      // 内部执行逻辑;
      const submitAnalyse = async (type: string) => {
        if (props.dynamicModal.type === "folder") {
          // ruleList.value = visibleConfig.FieldRule.filter((v: any) => v.FR_Enable === true);
          ruleList.value = visibleConfig.FieldRule.filter((v: any) => v.FR_Enable === true);
        }
        if (props.dynamicModal.type === "child") {
          // ruleList.value = childVisibleConfig.FieldRule.filter((v: any) => v.FR_Enable === true);
          ruleList.value = childVisibleConfig.FieldRule.filter((v: any) => v.FR_Enable === true);
        }
        const FieldRuleClass = new RuleClass({ modalFormData: toRaw(modalFormData), ruleList: ruleList.value }); // 执行字段规则类方法
        const newModalFormData = FieldRuleClass.SetEncrypt(); //加密
        const title = props.dynamicModal.title;
        const { tableSelect, childTableSelect, oldModalFormData } = dynamicStore; // 从pinia获取初始化配置数据(主要用于初始布局基础数据)
        const { treeNode } = catalogStore;
        const stateNum: any = {
          Collect: 1,
          Arrangement: 2,
          Storage: 3,
          Utilization: 4
        };
        let param = {};
        let Record_ID = "";
        if (props.dynamicModal.type === "folder") {
          switch (title) {
            case "新增":
              Record_ID = global.createID();
              param = {
                list: [
                  {
                    ...newModalFormData,
                    Record_ID: Record_ID,
                    FM_ID: props.self.routeData.fmid,
                    FMT_ID: props.self.routeData.fmtid,
                    Catalog_ID: dynamicStore.noCatalogStatus ? null : treeNode.Catalog_ID,
                    Fonds_ID: props.self.routeData.fondsId,
                    Status: stateNum[props.self.routeData.status],
                    Parent_ID: props.self.leftTreeObj ? undefined : props.self.fatherObj.Record_ID
                  }
                ],
                tableName: visibleConfig.FMT.FMT_TableName
              };
              vueAxios.post("Dynamic", param).then((res: any) => {
                cancel(); // 关闭弹框
                if (type === "modalFormData") {
                  dynamicStore.addTableData(res.List);
                } else if (type === "modalFormData2") {
                  new ButtonClick().ParentClickEvent("新增", props.self);
                  dynamicStore.addTableData(res.List);
                }
              });
              break;
            case "修改":
              const flag = isEqual(oldModalFormData, modalFormData);
              if (!flag) {
                param = {
                  list: [{ ...modalFormData, Catalog_ID: dynamicStore.noCatalogStatus ? null : treeNode.Catalog_ID }],
                  tableName: visibleConfig.FMT.FMT_TableName
                };
                await vueAxios.put("Dynamic", param).then((res: any) => {
                  if (res.Mark) {
                    dynamicStore.updateTableData(res.List[0]);
                    cancel(); // 关闭弹框
                  }
                });
                if (globalStore.showChild && props.self.childData.length > 0) {
                  await vueAxios
                    .get(
                      "Dynamic/CommonChildTableGet",
                      {
                        fmid: tableSelect[0].FM_ID,
                        dataId: tableSelect[0].Record_ID,
                        fmtType: props.self.childData[props.self.activeName].FMT_Type
                      },
                      { noLoading: true }
                    )
                    .then(res => {
                      dynamicStore.setChildTableData(res.List);
                      dynamicStore.setChildSourthTableData(res.List);
                    });
                }
              } else {
                cancel(); // 关闭弹框
              }
              break;
            case "克隆":
              Record_ID = global.createID();
              param = {
                list: [
                  {
                    ...newModalFormData,
                    Record_ID: Record_ID,
                    FM_ID: tableSelect[0].FM_ID,
                    FMT_ID: tableSelect[0].FMT_ID,
                    Catalog_ID: dynamicStore.noCatalogStatus ? null : tableSelect[0].Catalog_ID,
                    Fonds_ID: tableSelect[0].Fonds_ID,
                    Status: stateNum[props.self.routeData.status],
                    Parent_ID: tableSelect[0].Parent_ID
                  }
                ],
                tableName: visibleConfig.FMT.FMT_TableName
              };
              vueAxios.post("Dynamic", param).then((res: any) => {
                cancel(); // 关闭弹框
                if (type === "modalFormData") {
                  dynamicStore.addTableData(res.List[0]);
                } else if (type === "modalFormData2") {
                  new ButtonClick().ParentClickEvent("克隆", props.self);
                  dynamicStore.addTableData(res.List[0]);
                }
              });
              break;
          }
        }
        if (props.dynamicModal.type === "child") {
          switch (title) {
            case "新增":
              Record_ID = global.createID();
              param = {
                list: [
                  {
                    ...newModalFormData,
                    Record_ID: Record_ID,
                    FM_ID: tableSelect[0].FM_ID,
                    FMT_ID: props.self.childData[props.self.activeName].FMT_ID,
                    Catalog_ID: dynamicStore.noCatalogStatus ? null : tableSelect[0].Catalog_ID,
                    Fonds_ID: tableSelect[0].Fonds_ID,
                    Status: tableSelect[0].Status,
                    Parent_ID: props.self.tableSetting.rowClickObj.Record_ID
                  }
                ],
                tableName: childVisibleConfig.FMT.FMT_TableName
              };
              await vueAxios.post("Dynamic", param).then((res: any) => {
                cancel(); // 关闭弹框
                if (type === "modalFormData") {
                  dynamicStore.addChildTableData(res.List);
                } else if (type === "modalFormData2") {
                  new ButtonClick().ChildClickEvent("新增", props.self);
                  dynamicStore.addChildTableData(res.List);
                }
              });
              // 更新父级数据
              await vueAxios
                .get("Dynamic/CommonSingleDataGet", { fmtId: tableSelect[0].FMT_ID, Id: tableSelect[0].Record_ID })
                .then((res: any) => {
                  console.log(1111111111111, res);
                  dynamicStore.updateTableData(res.Model);
                });
              break;
            case "修改":
              const flag = isEqual(oldModalFormData, modalFormData);
              if (!flag) {
                param = {
                  list: [{ ...modalFormData, Catalog_ID: dynamicStore.noCatalogStatus ? null : tableSelect[0].Catalog_ID }],
                  tableName: childVisibleConfig.FMT.FMT_TableName
                };
                await vueAxios.put("Dynamic", param).then((res: any) => {
                  if (res.Mark) {
                    dynamicStore.updateChildTableData(res.List[0]);
                    cancel(); // 关闭弹框
                  }
                });
                // 更新父级数据
                await vueAxios
                  .get("Dynamic/CommonSingleDataGet", { fmtId: tableSelect[0].FMT_ID, Id: tableSelect[0].Record_ID })
                  .then((res: any) => {
                    console.log(1111111111111, res);
                    dynamicStore.updateTableData(res.Model);
                  });
              } else {
                cancel(); // 关闭弹框
              }
              break;
            case "克隆":
              Record_ID = global.createID();
              param = {
                list: [
                  {
                    ...newModalFormData,
                    Record_ID: Record_ID,
                    FM_ID: childTableSelect[0].FM_ID,
                    FMT_ID: childTableSelect[0].FMT_ID,
                    Catalog_ID: dynamicStore.noCatalogStatus ? null : childTableSelect[0].Catalog_ID,
                    Fonds_ID: childTableSelect[0].Fonds_ID,
                    Status: stateNum[props.self.routeData.status],
                    Parent_ID: childTableSelect[0].Parent_ID
                  }
                ],
                tableName: childVisibleConfig.FMT.FMT_TableName
              };
              vueAxios.post("Dynamic", param).then((res: any) => {
                cancel(); // 关闭弹框
                if (type === "modalFormData") {
                  dynamicStore.addChildTableData(res.List[0]);
                } else if (type === "modalFormData2") {
                  new ButtonClick().ChildClickEvent("克隆", props.self);
                  dynamicStore.addChildTableData(res.List[0]);
                }
              });
              break;
          }
        }
      };
      onMounted(() => {
        init();
      });
      // 监听表单属性值的变化
      watch(
        modalFormData,
        (newVal, oldVal) => {
          const stateNum: any = {
            Collect: 1,
            Arrangement: 2,
            Storage: 3,
            Utilization: 4
          };
          let FieldRuleClass = null;
          if (props.dynamicModal.title === "克隆") {
            newVal.Status = stateNum[props.self.routeData.status];
            FieldRuleClass = new RuleClass({
              modalFormData: newVal,
              ruleList: ruleList.value,
              tableName: tableName.value
            });
          } else {
            FieldRuleClass = new RuleClass({
              modalFormData: newVal,
              ruleList: ruleList.value,
              tableName: tableName.value
            }); // 执行字段规则类方法
          }
          FieldRuleClass.fieldRuleEvent2();
        },
        { immediate: true }
      );
      return {
        continuousSubmission,
        modalFormData,
        formRules,
        ruleList,
        modalFormRef,
        submitLoading,
        submitLoading2,
        dictionary,
        transTree,
        init,
        cancel,
        onSubmit,
        onSubmit2,
        changeTrigger,
        input,
        selectChange
      };
    },
    template: props.dynamicModal.htmlCode // 绑定模板
  });
  // 引入icon
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
  }
  // 挂载实例
  app.use(ElementPlus, { locale: zhCn }).mount("#dynamic-form");
};

defineExpose({ open });
</script>

<style scoped lang="scss">
.dynamicForm {
  :deep(.previewModel) {
    .button {
      .el-form-item__content {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
  :deep(.el-dialog__body) {
    padding: 0;
  }
  #dynamic-form {
    max-height: 65vh;
    padding: calc(var(--el-dialog-padding-primary)) var(--el-dialog-padding-primary);
    overflow: auto;
    .date {
      .el-input__wrapper {
        width: calc(100% - 22px);
      }
    }
  }
}
</style>
